﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Globalization;

namespace TSites.Administrator.Validation
{
	public class DateRangeAttribute : ValidationAttribute
	{
		private const string dateFormat = "dd/MM/yyyy";
		private const string defaultErrorMessage =
			   "'{0}' must be a date between {1} and {2}.";

		public DateTime MinDate { get; set; }
		public DateTime MaxDate { get; set; }

		public DateRangeAttribute()
			: base(defaultErrorMessage)
		{
			DateTime currentDate = DateTime.Today;
			MinDate = currentDate.AddYears(-150);
			MaxDate = currentDate.AddYears(-3);
		}

		public override bool IsValid(object value)
		{
			if (value == null || !(value is DateTime))
			{
				return true;
			}

			DateTime dateValue = (DateTime)value;
			return MinDate <= dateValue && dateValue <= MaxDate;
		}
		public override string FormatErrorMessage(string name)
		{
			return String.Format(CultureInfo.CurrentCulture,
				ErrorMessageString,
				name, MinDate.ToString(dateFormat), MaxDate.ToString(dateFormat));
		}

		private static DateTime ParseDate(string dateValue)
		{
			return DateTime.ParseExact(dateValue, dateFormat,
				 CultureInfo.InvariantCulture);
		}
	}
}